<?php
namespace bee;

define("DAO_POST_NONE", 0);
define("DAO_POST_SELECT", 1);
//define("DAO_POST_INSERT_ID", 2);
//define("DAO_POST_ALL", 3);
define("DAO_PK_AUTO", 256);

abstract class DAO2 extends object
{
  /**
   *
   * @var db
   */
  protected $__conn;
  /**
   *
   * @var \Exception
   */
  public    $__exception;
  protected $__table;
  protected $__insert_array;
  protected $__update_array;
  protected $__param_types;
  protected $__PKAutoNumber = true;

  private $DAO_props = array("_class", "__exception", "__conn", "__table", "cls_props", "__insert_array", "__update_array", "__param_types", "__withEvents", "__objectID", "__PKAutoNumber");

  public function SELECT($id = 0)
  {	if($id == 0)
  	{	$id = $this->id;
  	}
  	$c=$this->__conn;
  	$sqt = "SELECT * FROM " . $c->__NAME_OPEN . $this->__table . $this->__conn->__NAME_CLOSE . " WHERE id = :id";
  	//echo $sqt;
  	$stmt = $this->__conn->prepare($sqt);
  	$stmt->bindParam(":id", $id, \PDO::PARAM_INT);
  	$stmt->setFetchMode(\PDO::FETCH_INTO, $this);
  	if($stmt->execute())
  	{ if($red = $stmt->fetch(\PDO::FETCH_INTO ))
  	  {	foreach ($this as &$v)
            { if(is_string($v))
              { // //$v = iconv("Windows-1250", "UTF-8", $v);
              }
            }
  		return 1;
  	  }
  	}
      $where_refl = new \ReflectionClass(get_called_class());
  	$cls_props = $where_refl->getProperties();
  	foreach ($cls_props as $prop)
  	{ if(!in_array($prop->name, $this->DAO_props))
  	  {	$pn = $prop->name;
            $this->$pn="";
  	  }
  	}
  	return 0;
  }

  public function DELETE()
  {	$sqt = "DELETE FROM " . $this->__conn->__NAME_OPEN . $this->__table . $this->__conn->__NAME_CLOSE . " WHERE id = :id";
  	$stmt = $this->__conn->prepare($sqt);
  	$stmt->bindParam(":id", $this->id, \PDO::PARAM_INT);
  	if($stmt->execute())
  	{	return 1;
  	}
  	return 0;
  }

	/**
	 * @return int
	 */
  public function INSERT($params = DAO_POST_SELECT)
  {	try
    { $c = $this->__conn;
  	  $sqt = "INSERT INTO " . $c->__NAME_OPEN . $this->__table . $this->__conn->__NAME_CLOSE . " (" . $c->__NAME_OPEN
  	 . implode($c->__NAME_CLOSE . ", " . $c->__NAME_OPEN, $this->__insert_array) . $c->__NAME_CLOSE . ") VALUES (:"
  	 . implode(", :", $this->__insert_array) . ")";
  	  $cfg = config::getInstance();
  	//if($this->__table !='bee_loglog')
  	  //die("++++ $sqt +++<br />++" . print_r($this->__insert_array, true)  . " ++<br />");
  		$stmt = $this->__conn->prepare($sqt);
  		foreach ($this->__insert_array as $insert_field)
  		{ if($insert_field != "id")
  		  { // //$this->$insert_field = iconv("UTF-8", "Windows-1250",  $this->$insert_field);
  		  //echo "::" . $this->$insert_field . "::<br />";
  		    if(is_string($this->$insert_field))
  		    { // //$this->$insert_field = iconv("UTF-8", "Windows-1250", $this->$insert_field);
  		    } else
  		    {}
  			  $stmt->bindParam(":" . $insert_field, $this->$insert_field); // doraditi bindanje po tipu
  		  }
  			//echo "::" . $this->$insert_field . "::<br />";
  		}
  		/**
  		 * @todo problem kada pk nije autonumber
  		 */
  		if($stmt->execute())
  		{ if( ($params & DAO_POST_SELECT) == DAO_POST_SELECT)
  		  { //echo "=$params=";
  		    if(($cfg->sql__DATABASE_TYPE & DB_ENGINE_MSSQL) == DB_ENGINE_MSSQL && false)
    		{ $stmt = $this->__conn->query("SELECT @@IDENTITY");
              $row = $stmt->fetch(\PDO::FETCH_NUM);
              $this->SELECT($row[0]);
            } else
            { $this->SELECT($this->__conn->lastInsertId());
            }
            // echo " -- PS $sqt --  ";
  		  }
  		  return 1;
  		}
  		return 0;
    } catch(\Exception $ex)
    { //var_dump($ex);
      $this->__exception = $ex;
      return 0;
    }
  }

	public function UPDATE()
	{ $sqt = "UPDATE " . $this->__conn->__NAME_OPEN . $this->__table . $this->__conn->__NAME_CLOSE
	  . " SET " . implode(", ", $this->__update_array) . " WHERE id = :id";
	  $stmt = $this->__conn->prepare($sqt);
		//echo $sqt . "** " . print_r($this, true) . " **";
	  foreach ($this->__insert_array as $insert_field)
	  { $tif = "__" . $insert_field . "";
        if(is_string($this->$insert_field))
        { $this->$tif = $this->$insert_field;
      	  // //$this->$tif = iconv("UTF-8", "Windows-1250", $this->$insert_field);
        } else
        { $this->$tif = $this->$insert_field;
        }
        $stmt->bindParam(":" . $insert_field, $this->$tif);//, $this->param_types[$insert_field]); // doraditi bindanje po tipu
      }
      $stmt->bindParam(":id", $this->id, \PDO::PARAM_INT);

      if($stmt->execute())
      { return 1;
      }
      return 0;
	}

	function __construct($pk = 0, db2 $connection = NULL)
	{ if($connection)
	  { $this->__conn = $connection;
	  } else
	  { $this->__conn = db2::getInstance();
	  }
	  $this->__withEvents = false;

	  if($pk)
	  {	$this->SELECT($pk);
	  }
      $this->__table = str_replace("\\", "_", get_called_class());

      $where_refl = new \ReflectionClass(get_called_class());
      $cls_props = $where_refl->getProperties();
      $this->__insert_array = array();
      $this->__update_array = array();

      foreach ($cls_props as $prop)
      {	if(!in_array($prop->name, $this->DAO_props) && ($prop->name != "id" || $this->__PKAutoNumber == false))
      	{ $this->__update_array[$prop->name] = $this->__conn->__NAME_OPEN . $prop->name . $this->__conn->__NAME_CLOSE . " = :" . $prop->name;// . $daoRow->prepareSQL($daoRow->{$prop->name}, true);
      	  $this->__insert_array[":" .$prop->name] = $prop->name;
      	}
      }
	}

	public function getSysTable()
	{	return $this->__table;
	}
	public function geSysTable()
	{	return $this->__table;

	}
	public function getConn()
	{	return $this->__conn;
	}
	/*
	public static function prepareSQL($text, $addQuote = false, $trim = true, $empty2null = true)//deprecated???
	{	if (is_null($text) || (empty($text) && $empty2null && $text != "0"))
		{	return "NULL";
		}
		if($trim)
		{	$text = trim($text);
		}
		// //$text = iconv("utf-8", "windows-1250", str_ireplace("'", "''", $text));


		if($addQuote)// || !is_numeric($text))
		{	$text = "'$text'";
		}
		//echo $text;
		return $text;
	}
*/

	public function fillFromArray($array = "", $arr_prefix = "", $empty2null = true)//default $_REQUEST
	{	if(!is_array($array))
		{	$array = $_REQUEST;
		}
		$refl = new \ReflectionClass(get_class($this));
		//print_r($refl);
		$class_props = $refl->getProperties();
		//print_r($class_props);
		foreach ($class_props as $prop)
		{	if(isset($array[$arr_prefix . $prop->name]))// && !is_null($array[$arr_prefix . $prop->name]))// bilo isset(...)
			{	$pn = $prop->name;
				$this->$pn = $array[$arr_prefix . $pn];
			}
		}
	}


}
